﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;

namespace LOC
{
    class Program
    {
        private static string HelpFileName = "Help.txt";

        static void Main(string[] args)
        {

            Predicate<string[]> helpNeeded =
                a => a == null || a.Length == 0 || a[0] == "/?" || a[0] == "/h" || a[0] == "/help";

            if (helpNeeded(args))
                DisplayHelp();
            else
            {
                string path = Directory.GetCurrentDirectory();

                List<CountResult> counted = LineCounter.CountDir(path, args);

                // makes format string for table-like output, e.g. {0,13} {1}
                Func<int, string> formatColumn = width => "{0," + width + "}  {1}";

                int maxWidth = counted.Aggregate(0, (max, entry) => Math.Max(entry.FileName.Length, max));

                foreach (CountResult entry in counted)
                    Console.WriteLine(formatColumn(-maxWidth), entry.FileName, entry.LinesCount);

                int totalCount = counted.Aggregate(0, (count, entry) => count + entry.LinesCount);
                Console.WriteLine(formatColumn(maxWidth), "TOTAL", totalCount);
                //Console.ReadLine();
            }
        }

        static void DisplayHelp()
        {
            string resName = Assembly.GetExecutingAssembly().GetName().Name +
                '.' + HelpFileName;
            using (Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream(resName))
            {
                using (StreamReader reader = new StreamReader(s))
                {
                    string help = reader.ReadToEnd();
                    Console.WriteLine(help);
                }
            }
        }
    }
}
